<?php
namespace SmsAliba;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Sms extends Controller
{

    public $config;
    public function __construct()
    {
        parent::__construct();
        //接入阿里云短信服务
        $client =getConfig("client");
        //短信模板配置
        $templateList = getConfig("template.register");
        //平台服务配置
        $this->config['service'] = [
            "accessKeyId"     => $client['accessKeyId'],
            "accessKeySecret" => $client['accessKeySecret'],
            "regionId"        => 'cn-hangzhou'
        ];
        if($templateList){
            $this->config['template'] = $templateList;
        }else{
            $this->config['template'] = [
                //指定产品
                "product"        => "Dysmsapi",
                //请求方式
                "method"         => "post",
                //版本请求设置
                "version"        => "2017-05-25",
                //动作设置
                "action"         => "SendSms",
                //host 主机设置
                "host"           => "dysmsapi.aliyuncs.com",
                //协议设置 https | http
                "scheme"         => "https",
                //模板参数
                "options" => [
                    "query"=>[
                        //地区
                        'RegionId' => "cn-hangzhou",
                        //手机号
                        "PhoneNumbers" =>[],
                        //薄板签名，
                        "SignName"     => "",
                        //模板代码
                        "TemplateCode" => "",
                        //发送内容 {code : 'test'}，所对应得内容
                        "TemplateParam"=> [
                            "code"=>''
                        ]
                    ]
                ],
            ];
        }
    }

    /**
     * @Notes:获取配置
     * @User: chenping
     * @email: 375129701@qq.com
     * @return mixed
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @Notes:设置短信平台key
     * @User: chenping
     * @email: 375129701@qq.com
     * @param $signName
     */
    public function setAccessKeyId($key)
    {
        $this->config['service']['accessKeyId'] = $key;
    }

    /**
     * @Notes:设置短信平台key
     * @User: chenping
     * @email: 375129701@qq.com
     * @param $signName
     */
    public function setAccessKeySecret($cert)
    {
        $this->config['service']['accessKeySecret'] = $cert;
    }


    /**
     * @Notes:设置短信密钥
     * @User: chenping
     * @email: 375129701@qq.com
     * @param $signName
     */
    public function setSignName($signName)
    {
        $this->config['template']['options']['query']['SignName'] = $signName;
    }

    /**
     * @Notes:设置短信模板代码
     * @User: chenping
     * @email: 375129701@qq.com
     * @param $signName
     */
    public function setTemplateCode($templateCode)
    {
        $this->config['template']['options']['query']['TemplateCode'] = $templateCode;
    }

    /**
     * @Notes:设置短信模板发送内容
     * @User: chenping
     * @email: 375129701@qq.com
     * @param $signName
     */
    public function setTemplateContent($templateContent,$type)
    {
        $content = [];
        switch ($type)
        {
            case 1:
                $content['name'] = $templateContent;
                break;
            case 2:
                $content['code'] = $templateContent;
                break;
            case 3:
                $content['name'] = $templateContent;
                break;
        }
        $this->config['template']['options']['query']['TemplateParam'] = $content;
    }



    /**
     * @Notes:发送短信
     * @User: chenping
     * @email: 375129701@qq.com
     * @param string $tel 手机号
     * @param string $template 短信模板
     * @return array
     */
    public  function sendSms($tel='',$content='',$template='register')
    {
        if( empty($tel)  ) return error('请填写手机号码');

        if( empty($template) ) return error('请填写短信模板');

        //$templateList = getConfig("template.".$template);

        //if(!$templateList) return error('请完善短信模板配置');

        if( is_array($tel) )
        {
            if(count($tel)>1000) return $this->error("一次性最多处理1000个手机号码");

            $newTel = [];

            //检测合法性
            for ($i=0;$i<count($tel);$i++)
            {
                //正确数据
                if (preg_match("/^1[3-9]{1}[0-9]{9}$/", $tel[$i]))
                {
                    $newTel['success'][] = $tel[$i];
                    //错误数据
                } else {
                    $newTel['error'][] = $tel[$i];
                }
            }

            if( !isset($newTel['success']) ) return $this->error("请检查数据是否正确",$newTel);

            $tel = implode(",",$newTel['success']);
        }

        $this->config['template']['options']['query']['PhoneNumbers']  = $tel;

        //if(isset($this->config['template']['options']['query']['TemplateParam']['code']))  $this->config['template']['options']['query']['TemplateParam']['code'] = $content;
        //if(isset($this->config['template']['options']['query']['TemplateParam']['name']))  $this->config['template']['options']['query']['TemplateParam']['name'] = $content;

        $this->config['template']['options']['query']['TemplateParam'] = json_encode( $this->config['template']['options']['query']['TemplateParam']);

        AlibabaCloud::accessKeyClient($this->config['service']['accessKeyId'],$this->config['service']['accessKeySecret'])
            ->regionId($this->config['service']['regionId'])
            ->asDefaultClient();

        try{
            $result =  AlibabaCloud::rpc()
                ->product($this->config['template']['product'])
                ->version($this->config['template']['version'])
                ->action($this->config['template']['action'])
                ->method($this->config['template']['method'])
                ->scheme($this->config['template']['scheme'])
                ->host($this->config['template']['host'])
                ->options($this->config['template']['options'])
                ->request();
            $data = $result->toArray();
            if($data['Code']=='OK') return success("success",$data);
            return error($data['Message'],$data);
        }catch (ClientException $exception){
            return error($exception->getMessage());
        }catch (ServerException $exception){
            return error($exception->getMessage());
        }
    }
}